<template>
  <view class="flex-col-center min-h-screen bg-gray-50 p-4">
    <!-- 使用UnoCSS原子类 -->
    <image class="w-200rpx h-200rpx mb-4" src="/static/logo.png"></image>

    <view class="text-center mb-6">
      <text class="text-36rpx text-gray-600 font-bold">{{ title }}</text>
    </view>

    <!-- 用户信息 -->
    <view class="card w-full max-w-400rpx mb-6">
      <text class="text-20rpx font-semibold mb-4 text-center">用户状态</text>

      <view v-if="userStore.isLoggedIn" class="text-center">
        <text class="text-16rpx text-gray-600">欢迎, {{ userStore.userName }}!</text>
        <u-button type="error" size="mini" class="mt-2" @click="handleLogout">退出登录</u-button>
      </view>

      <view v-else class="text-center">
        <text class="text-16rpx text-gray-600 mb-2">未登录</text>
        <u-button type="primary" size="mini" @click="handleLogin">登录</u-button>
      </view>

      <!-- 持久化提示 -->
      <view class="mt-4 p-2 bg-blue-50 rounded">
        <text class="text-12rpx text-blue-600 text-center">💾 用户状态已自动保存到本地存储</text>
      </view>
    </view>

    <!-- UnoCSS按钮样式 -->
    <view class="flex-center gap-4 mb-6">
      <view class="btn-primary px-6 py-3 rounded-lg" @click="showToast('UnoCSS按钮点击')">
        <text class="text-white">UnoCSS按钮</text>
      </view>
      <view class="btn-secondary px-6 py-3 rounded-lg" @click="showModal('提示', '这是一个模态框')">
        <text class="text-white">次要按钮</text>
      </view>
    </view>

    <!-- uview-plus按钮 -->
    <view class="flex-center gap-4 mb-4">
      <u-button type="primary" @click="showLoading('加载中...')">uview-plus按钮</u-button>
      <u-button type="success" @click="goToListPage">分页列表</u-button>
    </view>

    <!-- 卡片示例 -->
    <view class="card w-full max-w-300rpx mb-6">
      <text class="text-18rpx font-semibold mb-2">UnoCSS卡片</text>
      <text class="text-14rpx text-gray-500">这是一个使用UnoCSS原子类构建的卡片组件</text>
    </view>

    <!-- 持久化测试 -->
    <view class="card w-full max-w-400rpx mb-6">
      <text class="text-18rpx font-semibold mb-4 text-center">持久化测试</text>

      <view class="flex-center gap-2 mb-4">
        <u-button type="info" size="mini" @click="testPersistence">测试持久化</u-button>
        <u-button type="warning" size="mini" @click="clearAllStorage">清除所有存储</u-button>
      </view>

      <text class="text-12rpx text-gray-500 text-center">点击"测试持久化"查看存储状态，点击"清除所有存储"重置所有数据</text>
    </view>

    <!-- 应用更新测试 -->
    <view class="card w-full max-w-400rpx">
      <text class="text-18rpx font-semibold mb-4 text-center">应用更新测试</text>

      <view class="flex-center gap-2 mb-4">
        <u-button type="primary" size="mini" @click="checkUpdate">检查更新</u-button>
      </view>

      <text class="text-12rpx text-gray-500 text-center">
        <!-- #ifdef APP-PLUS -->
        点击"检查更新"测试应用更新功能
        <!-- #endif -->
        <!-- #ifndef APP-PLUS -->
        更新功能仅在 App 环境中可用
        <!-- #endif -->
      </text>
    </view>
  </view>
</template>

<script>
import { useUserStore } from '@/stores';
import { appUpdate } from '@/utils/appUpdate.js';
import { useT } from '@/utils/i18n';

export default {
  data() {
    return {
      title: 'MasterCard - Pinia 状态管理'
    };
  },

  setup() {
    // 使用 Pinia stores
    const userStore = useUserStore();

    return {
      userStore
    };
  },

  onLoad() {
    // 初始化用户状态
    this.userStore.initFromStorage();
  },

  methods: {
    async handleLogin() {
      uni.showLoading({ title: '登录中...' });

      try {
        const result = await this.userStore.login();

        uni.hideLoading();

        if (result.success) {
          this.showToast('登录成功');
        } else {
          this.showToast(`登录失败: ${result.error}`);
        }
      } catch {
        uni.hideLoading();
        this.showToast('登录出错');
      }
    },

    handleLogout() {
      this.userStore.logout();
      this.showToast('已退出登录');
    },

    testPersistence() {
      const storageKeys = ['user-store'];
      const storageInfo = storageKeys
        .map((key) => {
          const data = uni.getStorageSync(key);
          return `${key}: ${data ? '已存储' : '未存储'}`;
        })
        .join('\n');

      this.showModal('存储状态', storageInfo);
    },

    clearAllStorage() {
      this.showModal('确认清除', '确定要清除所有本地存储数据吗？').then((confirmed) => {
        if (confirmed) {
          // 清除所有 Pinia 存储
          uni.removeStorageSync('user-store');

          // 重置用户状态
          this.userStore.logout();

          this.showToast('已清除所有存储数据');
        }
      });
    },

    showToast(title, icon = 'none', duration = 2000) {
      uni.showToast({
        title,
        icon,
        duration
      });
    },

    showModal(title, content) {
      return new Promise((resolve) => {
        uni.showModal({
          title,
          content,
          success: (res) => {
            resolve(res.confirm);
          }
        });
      });
    },

    showLoading(title = '加载中...') {
      uni.showLoading({ title });
    },

    // 检查更新
    async checkUpdate() {
      // #ifdef APP-PLUS
      try {
        uni.showLoading({ title: useT('检查更新中.') });
        const hasUpdate = await appUpdate(true); // 手动检查
        uni.hideLoading();

        if (hasUpdate) {
          console.log('发现新版本，正在处理更新...');
        } else {
          console.log('当前已是最新版本');
        }
      } catch (error) {
        uni.hideLoading();
        console.error('检查更新失败:', error);
        uni.showToast({
          title: '检查更新失败',
          icon: 'none'
        });
      }
      // #endif

      // #ifndef APP-PLUS
      uni.showToast({
        title: '更新功能仅在 App 环境中可用',
        icon: 'none'
      });
      // #endif
    },

    // 跳转到列表页面
    goToListPage() {
      uni.navigateTo({
        url: '/pages/list/list'
      });
    }
  }
};
</script>

<style lang="scss">
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.logo {
  height: 200rpx;
  width: 200rpx;
  margin-top: 200rpx;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 50rpx;
}

.text-area {
  display: flex;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  color: #8f8f94;
}
</style>
